package com.declum.peyar.db;

import java.util.HashMap;
import java.util.Map;

/**
 * This is the Naming Database for Peyar project. Now its a in-memory data base. <br>
 * This holds the Service/Address pair binding which are registered with this
 * Naming Service
 * 
 * @author Clement
 * 
 */
public class PeyarDB {
	Map<String, Record> records = new HashMap<String, Record>();

	/**
	 * This is used to bind a address to a name. Address is a Unique identifier
	 * in the network to identify the Physical location of the resource. But
	 * name is a Unique to a service. A Service can have one or more physical
	 * identifiers.
	 * 
	 * @param name
	 *            Service name
	 * @param address
	 *            IP Address
	 * @return true for successful bindings, false if not
	 */
	public boolean bind(String name, String address) {
		Record record = this.records.get(name);
		if (record == null) {
			record = new Record();
			this.records.put(name, record);
		}

		if (!record.isAddressFound(address)) {
			record.addAddress(address);
		} else {
			return false;
		}

		return true;
	}

	/**
	 * This method used to get identifier associated with this Service.
	 * 
	 * @param name
	 *            Service name
	 * @return list of identifiers to of the Service. if no identifier found, it
	 *         returns an array of size zero
	 */
	public String[] lookup(String name) {
		Record record = this.records.get(name);
		if (record != null) {
			return record.getAddresses();
		} else {
			return new String[] {};
		}
	}

	/**
	 * This method will remove the bind of address to the Service se\pecified
	 * 
	 * @param name
	 * @param address
	 */
	public void unbind(String name, String address) {
		Record record = this.records.remove(name);
		if (record == null) {
			return;
		}

		if (record.isAddressFound(address)) {
			record.removeAddress(address);
		}

	}
}
